<?php
	/*第三方登录*/
	switch($action){
		case 'sinaweibo':
			
		break;
		case 'qzone':
			session_start();
	
			/**
			 * 在你运行本demo之前请到 http://connect.opensns.qq.com/申请appid, appkey, 并注册callback地址
			 */
			//申请到的appid
			//$_SESSION["appid"]    = yourappid; 
			$_SESSION["appid"]    = 100297168; 
			
			//申请到的appkey
			//$_SESSION["appkey"]   = "yourappkey"; 
			$_SESSION["appkey"]   = "b8cee8a4a93d5f2ba8822b8d2a96b321"; 
			
			//QQ登录成功后跳转的地址,请确保地址真实可用，否则会导致登录失败。
			//$_SESSION["callback"] = "http://your domain/oauth/get_access_token.php"; 
			$_SESSION["callback"] = SITE_URL."?module=member&file=connect&action=qzone";
			
			//QQ授权api接口.按需调用
			$_SESSION["scope"] = "get_user_info,add_share,list_album,add_album,upload_pic,add_topic,add_one_blog,add_weibo";
			
			//print_r ($_SESSION);
			
			
			// 返回
			if($code){
				//debug
				//print_r($_REQUEST);
				//print_r($_SESSION);
			
				/*安全性检查*/
				/*if($_REQUEST['state'] == $_SESSION['state']) //csrf
				{*/
					$token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
						. "client_id=" . $_SESSION["appid"]. "&redirect_uri=" . urlencode($_SESSION["callback"])
						. "&client_secret=" . $_SESSION["appkey"]. "&code=" . $_REQUEST["code"];
			
					$response = get_url_contents($token_url);
					if (strpos($response, "callback") !== false)
					{
						$lpos = strpos($response, "(");
						$rpos = strrpos($response, ")");
						$response  = substr($response, $lpos + 1, $rpos - $lpos -1);
						$msg = json_decode($response);
						if (isset($msg->error))
						{
							echo "<h3>error:</h3>" . $msg->error;
							echo "<h3>msg  :</h3>" . $msg->error_description;
							exit;
						}
					}
			
					$params = array();
					parse_str($response, $params);
			
					//debug
					//print_r($params);
			
					//set access token to session
					$_SESSION["access_token"] = $params["access_token"];
					
					// 获取OPENID
					$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" 
					. $_SESSION['access_token'];
			
					$str  = get_url_contents($graph_url);
					if (strpos($str, "callback") !== false)
					{
						$lpos = strpos($str, "(");
						$rpos = strrpos($str, ")");
						$str  = substr($str, $lpos + 1, $rpos - $lpos -1);
					}
				
					$user = json_decode($str);
					if (isset($user->error))
					{
						echo "<h3>error:</h3>" . $user->error;
						echo "<h3>msg  :</h3>" . $user->error_description;
						exit;
					}
				
					//debug
					//echo("Hello " . $user->openid);
					
					
				
					//set openid to session
					$_SESSION["openid"] = $user->openid;
					
					
					/*获取用户资料*/
					$graph_url = "https://graph.qq.com/user/get_user_info?access_token=".$_SESSION["access_token"]."&oauth_consumer_key=".$_SESSION["appid"]."&openid=".$_SESSION["openid"]."&format=json";
					
					$str  = get_url_contents($graph_url);
				
					if($str!==FALSE){
						$result = json_decode($str,true);
						if($result["ret"]==0){
							/*echo "<tr><td class='narrow-label'>用户昵称:</td><td>".$result["nickname"]."</td></tr>";
							echo "<tr><td class='narrow-label'>小等头像:</td><td><img src='".$result["figureurl"]."' border='0' /></td></tr>";
							echo "<tr><td class='narrow-label'>中等头像:</td><td><img src='".$result["figureurl_1"]."' border='0' /></td></tr>";
							echo "<tr><td class='narrow-label'>大等头像:</td><td><img src='".$result["figureurl_2"]."' border='0' /></td></tr>";
							echo "<tr><td class='narrow-label'>用户性别:</td><td>".$result["gender"]."</td></tr>";
							echo "<tr><td class='narrow-label'>用户黄钻:</td><td>".$result["vip"]."</td></tr>";
							echo "<tr><td class='narrow-label'>黄钻等级:</td><td>".$result["level"]."</td></tr>";*/
							
							$memberinfo = $db->get_one("select `userid`,`username`,`password`,`email`,`modelid`,`avatar`,`openid`,`nickname` from ".DB_PRE."member where `openid` = '".$_SESSION["openid"]."'");
							
							$userid = $memberinfo['userid'];
							$md5_password = $memberinfo['password'];
							
							if(!$memberinfo){
								/*注册*/
								$memberinfo['username'] = 'temp_'.time();
								$memberinfo['password'] = '123456';
								$memberinfo['email'] = 'sss@qq.com';
								$memberinfo['modelid'] = '10';
								$memberinfo['avatar'] = $result["figureurl_2"];
								$memberinfo['openid'] = $_SESSION["openid"];
								$memberinfo['nickname'] = $result["nickname"];
								
								/*加载语言包*/
								require_once MOD_ROOT.'member/member.lang.php';
								require_once MOD_ROOT.'member/member_admin.lang.php';
				
								if(!$userid)
								{
									$userid = $member->register($memberinfo);
								}
								if(!$userid) showmessage($member->msg(), SITE_URL);
								
								$md5_password = $member->password($memberinfo['password']);
								
							}
							
							
							
							/*$db->insert(DB_PRE.'member',$memberinfo);
							if($db->insert_id()){
								showmessage('注册成功！');
							}*/
							
							
							
							
							//setcookie('auth', $site_auth,time()+3600*24);
							//setcookie('cookietime', $_cookietime, time()+3600*24);
							//setcookie('username', $memberinfo['username'],time()+3600*24);
							/*
								自动登录
							*/
							//if(!$M['enablemailcheck'] && !$M['enableadmincheck'])
							//{
								$site_auth_key = md5(AUTH_KEY.$_SERVER['HTTP_USER_AGENT']);
								$site_auth = site_auth($userid."\t".$md5_password, 'ENCODE', $site_auth_key);
								
								$username = $memberinfo['nickname'] ? $memberinfo['nickname'] : $memberinfo['username'];
								
								/*set_cookie('auth', $site_auth, 0);
								set_cookie('username', $memberinfo['username'], 0);*/
								
								$script = "<script language='javascript'>";
								$script .= "setcookie('auth', '".$site_auth."', 0);";
								$script .= "setcookie('username', '".$username."', 0);";
								//$script .= "window.opener.location.href = window.opener.location.href; ";
								$script .= "window.opener.location.reload();";
								$script .= "window.close(); ";
								$script .= "</script>";
							//}
										
							showmessage('登录成功！'.$script, SITE_URL);
							
							
						}else{
							echo "<tr><td class='narrow-label'>反馈消息:</td><td>".$result["msg"]."</td></tr>";
						}
					}else{
						echo "<tr><td class='narrow-label'>反馈消息:</td><td>获取用户信息失败。</td></tr>";
					}
			
				/*}
				else 
				{
					echo("The state does not match. You may be a victim of CSRF.");
				}*/
			}
			else{
				$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
				$login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" 
					. $_SESSION["appid"] . "&redirect_uri=" . urlencode($_SESSION["callback"])
					. "&state=" . $_SESSION['state']
					. "&scope=".$_SESSION["scope"];
				header("Location:$login_url");
			}
		break;
		case 'douban':
			
		break;
		case 'renren':
			
		break;
		case 'qqweibo':
			echo 1;
		break;
		case 'msn':
			
		break;
		default:
			include template('connect.html','member');
		break;
	}
	
	
	
	
	
	
	/*常用方法*/
	function do_post($url, $data)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
		curl_setopt($ch, CURLOPT_POST, TRUE); 
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
		curl_setopt($ch, CURLOPT_URL, $url);
		$ret = curl_exec($ch);
	
		curl_close($ch);
		return $ret;
	}
	
	function get_url_contents($url)
	{
		/*if (ini_get("allow_url_fopen") == "1")
		
			return file_get_contents($url);*/
	
		/*$ch = curl_init();
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_URL, $url);
		$result =  curl_exec($ch);
		curl_close($ch);
	
		return $result;*/
		
		$ch = curl_init();
		if(stripos($url,"https://")!==FALSE){
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		}
	
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
		$result = curl_exec($ch);
		$status = curl_getinfo($ch);
		curl_close($ch);
		
		if(intval($status["http_code"])==200){
			return $result;
		}else{
			echo "返回出错:<pre>".$status["http_code"].",请检查参数或者确实是腾讯服务器出错咯。</pre>";
			return false;
		}
	}
?>